package com.wly.packet;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.InvalidProtocolBufferException;
import com.wly.datapool.SessionManager;
import com.wly.datapool.playerpool.BasePlayer;
import com.wly.define.CommandCodeDefine;
import com.wly.define.PacketDefine;
import com.wly.define.SessionAttributeDefine;
import com.wly.gpb.BaseIntMessage.IntMessage.Builder;
import com.wly.gpb.Login.LogIn;
import com.wly.utils.CommonUtils;
import com.wly.utils.DataFactory;

public class CSLoginPacket extends CSPacket
{
	static private Logger log = LoggerFactory.getLogger("CSLoginPacket");
	//static private Logger log = new Logger;
	public void CSLoginPacket()
	{
	}
	
	@Override
	protected String getGPBClassName()
	{
		return "com.wly.gpb.Login$LogIn";
	}
	
	@Override
	public int getPacketID()
	{
		return PacketDefine.CS_LOGIN;
	}
	
	@Override
	public String toString()
	{
		return "CSLoginPacket packetID:"+getPacketID()+" "+getGPBClassName()+"\ncontent:\n"+content.toString();
	}

	@Override
	public void processMessage(IoSession session)
	{
		System.out.println("processmessage "+session.toString());
		LogIn loginInfo = (LogIn)content;
		int val;
		if(CommonUtils.checkPassword(loginInfo.getUserName(), loginInfo.getPassword()))
		{
			SCIntMessage msg = new SCIntMessage();
			Builder bulder= (Builder) msg.getBuilder();
			bulder.setType(PacketDefine.CS_LOGIN);
			bulder.setRet(CommandCodeDefine.WLY_OK);
			msg.build();
//			System.out.println("send player");
//			BasePlayer player = DataFactory.createNewPlayer(loginInfo.getUserName());
//			System.out.println(player.getName());
//			SCPlayer scPlayer = DataFactory.builderPlayerMessageByPlayer(player);
//			System.out.println("build scPlayer");
//			session.write(scPlayer);
			SCPlayer scPlayer = DataFactory.builderPlayerMessageByPlayer(DataFactory.createNewPlayer(loginInfo.getUserName()));
			session.setAttribute(SessionAttributeDefine.PLAYER, scPlayer);
			SessionManager.getInstance().addSession(session);
			session.write(scPlayer);
		}
		else
		{
			SCIntMessage msg = new SCIntMessage();
			Builder bulder= (Builder) msg.getBuilder();
			bulder.setType(PacketDefine.CS_LOGIN);
			bulder.setRet(CommandCodeDefine.WLY_ERR);
			msg.build();
			session.write(msg);
		}
	}
}
